import Toast from '../@vant/weapp/toast/toast';
import {ApiRootUrl} from "../config/index"
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('') + '' + [hour, minute, second].map(formatNumber).join('')
}
function getAnalysisIdCard(card, num) {
  if (num == 1) {
    //获取出生日期
    let birth = card.substring(6, 10) + "-" + card.substring(10, 12) + "-" + card.substring(12, 14);
    return birth;
  }
  if (num == 2) {
    //获取性别
    if (parseInt(card.substr(16, 1)) % 2 == 1) {
      //男
      return "男";
    } else {
      //女
      return "女";

    }
  }
  if (num == 3) {

    //获取年龄

    var myDate = new Date();

    var month = myDate.getMonth() + 1;

    var day = myDate.getDate();

    var age = myDate.getFullYear() - card.substring(6, 10) - 1;

    if (card.substring(10, 12) < month || card.substring(10, 12) == month && card.substring(12, 14) <= day) {

      age++;

    }

    return age;

  }

}
function formatDateTime(inputTime) {
  var date = new Date(inputTime);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return y + '-' + m + '-' + d;
};
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function request(url, data = {}, method = "POST") {
  //请求数据打印
  console.log("请求路径", url)
  console.log("请求数据", JSON.parse(JSON.stringify(data)))
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      success: function (res) {
        //打印请求结果
        console.log("请求结果：", res)
        if (res.data.code == 20000) {
          resolve(res.data);
        }else if(res.data.code == 30002){
          wx.hideLoading()
          Toast.clear();
          let info = wx.getStorageSync('qrcodeInfo')
          //重新检查用户session
          if(info.componentType == 0 || info.componentType == 1){
            wx.redirectTo({
              url: `/pages/firstpage/firstpage?componentType=${info.componentType}&OrgCode=${info.OrgCode}&orgName=${info.orgName}`,
            })
          }
          if(info.componentType == 5 || info.componentType == 6){
            wx.redirectTo({
              url: `/pages/serviceregister/serviceregister?componentType=${info.componentType}&OrgCode=${info.OrgCode}&orgName=${info.orgName}`,
            })
          }
        }else if(res.data.code == 30000){
          Toast.clear();
          wx.hideLoading()
          //重新登陆
          let info = wx.getStorageSync('qrcodeInfo')
          reLogin(info)
        }else {
          reject(res.data);
        }
      },
      
      fail: function (err) {
        console.log("--------->",err)
        Toast.clear();
        wx.hideLoading()
        Modal({message:"网络异常"})
      }
    })
  })
};
function login (){
  return new Promise((resolve,reject)=>{
    wx.login({
      success: res => {
        console.log('res=====>:',res);
        // return
        if (res.code) {
          wx.setStorageSync("code",res.code)
          let url = `${ApiRootUrl}/index/login/${res.code}`;
          console.log("url==>",url)
          wx.request({
            url:  url,
            method: 'GET',
            success(res) {
              console.log("接口返回数据：",res.data)
              if(res.data.code == 20000){
                let openId = res.data.data;
                console.log("接口返回数据：",res.data.data)
                wx.setStorageSync("openId",openId);
                console.log("sessionid==>",res.header["Set-Cookie"])
                wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
                resolve()    
              }else{
                Toast({
                  duration:3000,
                  forbidClick:true,
                  type: 'fail',
                  message: res.data.message,
                });
              }
            },
            fail(res) {
              console.log("err=>",res)
              Toast({
                duration:3000,
                forbidClick:true,
                type: 'fail',
                message: '网络已断开',
              });
            }
          })
          } else {
          console.log('登录失败！' + res.errMsg)
          }
      },
      fail:err =>{
        console.log("wx登陆错误===》",err)
      }
    })
  })
}
/*
  两个字符串时间 比较 
  params1 : eg:19940101
  params2 : eg:19940101
  return :bol (params1>params2)
*/
function judgeData(text1,text2){
  var year1 = text1.substring(0,4);
  var month1 = text1.substring(4,6);
  var day1 = text1.substring(6,8);
  var year2 = text2.substring(0,4);
  var month2 = text2.substring(4,6);
  var day2 = text2.substring(6,8);
  let value1 = year1+"-"+month1+"-"+day1
  let value2 = year2+"-"+month2+"-"+day2
  return value1 >= value2
}

function reLogin(info){
  wx.login({
    success: res => {
      console.log('res=====>:',res);
      // return
      if (res.code) {
        wx.setStorageSync("code",res.code)
        let url = `${ApiRootUrl}/index/login/${res.code}`;
        console.log("url==>",url)
        wx.request({
          url:  url,
          method: 'GET',
          success(res) {
            console.log("接口返回数据：",res.data)
            if(res.data.code == 20000){
              let openId = res.data.data;
              wx.setStorageSync("openId",openId);
              wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
              if(info.componentType == 0 || info.componentType == 1){
                wx.redirectTo({
                  url: `/pages/firstpage/firstpage?componentType=${info.componentType}&OrgCode=${info.OrgCode}&orgName=${info.orgName}`,
                })
              }
              if(info.componentType == 5 || info.componentType == 6){
                wx.redirectTo({
                  url: `/pages/serviceregister/serviceregister`,
                })
              }               
            }else{
              Toast({
                duration:3000,
                forbidClick:true,
                type: 'fail',
                message: res.data.message,
              });
            }
          },
          fail(res) {
            console.log("err=>",res)
            Toast({
              duration:3000,
              forbidClick:true,
              type: 'fail',
              message: '网络已断开',
            });
          }
        })
        } else {
          wx.showModal({
            title: '提示',
            showCancel:false,
            content: '微信登录失败！请退出重新登陆',
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
    },
    fail:err =>{
      wx.showModal({
        title: '提示',
        showCancel:false,
        content: '微信登录失败！请退出重新登陆',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      
    }
  })
}
function formatStringTime(time) {
  return time.split("-")[0] + time.split("-")[1] + time.split("-")[2]
}
/**
 * 
 * @param {time} timestamp 
 * @returns time
 */
function timestamp2time(timestamp){
  let seconeds = timestamp/1000
  if(seconeds < 60){
    return  Math.round(seconeds)+"秒" 
  }
  let min = seconeds/60
  let seconed = seconeds % 60
  let M = Math.round(min)
  let S = Math.round(seconed)
  console.log("S =>",S)
  let mins =  M< 10 ?"0"+M:M
  let secns = S < 10 ? "0"+S:S
  return mins+"分"+secns+"秒";
}
//文本 Toast
function Tosat(message){
  wx.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })
}
//成功 Toast
function SuccessTosat(message){
  wx.showToast({
    title: message,
    icon: 'success',
    duration: 2000
  })
}
//失败 Toast
function ErrorTosat(message){
  wx.showToast({
    title: message,
    icon: 'error',
    duration: 2000
  })
}
function Modal({title="提示",message,cancel=false}){
  return new Promise((reslove,reject)=>{
    wx.showModal({
      title: title,
      content: message,
      showCancel:cancel,
      success (res) {
        if (res.confirm) {
          reslove()
        } else if (res.cancel) {
          reject()
        }
      }
    })
  })
  
  
}
const formatTime2 = date => {
  let data1 = new Date(date)
  const year = data1.getFullYear()
  const month = data1.getMonth() + 1
  const day = data1.getDate()
  // const hour = data1.getHours()
  // const minute = data1.getMinutes()
  // const second = date.getSeconds()

  return [year, month,day].map(formatNumber).join('/') 
}
const formatTime1 = date => {
  let data1 = new Date(date)
  const year = data1.getFullYear()
  const month = data1.getMonth() + 1
  // const day = data1.getDate()
  // const hour = data1.getHours()
  // const minute = data1.getMinutes()
  // const second = date.getSeconds()

  return [year, month].map(formatNumber).join('/') 
}
const isPhone = value =>{
  var reg = /^([1][3,4,5,7,8][0-9]{9},?)+$/;
  return reg.test(value)
}
const isName = (value) =>{
  var reg = /^([\u4e00-\u9fa5],?)+$/;
  return reg.test(value)
}
const isChinese = (value)=>{
  var reg = /^[\u4e00-\u9fa5]+$/
  return reg.test(value)
}
module.exports = {
  formatTime,
  request,
  judgeData,
  formatDateTime,
  formatStringTime,
  login,
  timestamp2time,
  Tosat,
  Modal,
  ErrorTosat,
  SuccessTosat,
  formatTime1,
  formatTime2,
  isPhone,
  isName,
  isChinese,
  getAnalysisIdCard
}